package com.supply.dl.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.supply.dl.R;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.adapter.NormalPositionAdapter;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.bean.BaseItemBean;
import com.supply.dl.bean.EventBusImage;
import com.supply.dl.bean.JobAttachBean;
import com.supply.dl.bean.JobInfoBean;
import com.supply.dl.bean.OperateFlagEnum;
import com.supply.dl.bean.PositionInfoBean;
import com.supply.dl.bean.SearchStockBean;
import com.supply.dl.bean.SelectDictionaryBean;
import com.supply.dl.bean.TransGoodsBean;
import com.supply.dl.bean.TransferDetails;
import com.supply.dl.bean.WorkInfoBean;
import com.supply.dl.bean.WorkNotesBean;
import com.supply.dl.bean.request.SaveTransferGoodsRequest;
import com.supply.dl.constant.Constants;
import com.supply.dl.http.HttpManger;
import com.supply.dl.utils.BigDecimalUtil;
import com.supply.dl.utils.CommonNormalAdapterUtil;
import com.supply.dl.utils.DateUtils;
import com.supply.dl.utils.InterfaceUtil;
import com.supply.dl.utils.RecyclerViewUtil;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.utils.Utils;
import com.supply.dl.utils.utils.FileUtils;
import com.supply.dl.utils.utils.ToastUtil;
import com.supply.dl.view.MaxRecyclerView;
import com.supply.dl.view.RecycleScrollView;
import com.supply.dl.widget.LoadTipFailedLayout;
import com.supply.dl.widget.adapter.CommonNormalAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 移库收货详情
 * Created by Leng on 2018/8/31.
 */
public class TransferGoodsConfirmDetailActivity extends BaseActivity {

	/**
	 * activity标识
	 */
	private int activityFlag;
	@BindView(R.id.rs)
	RecycleScrollView rs;

	/**
	 * 物料列表
	 */
	@BindView(R.id.materail_rc)
	MaxRecyclerView materielRecyclerView;


	/**
	 * 加载框
	 */
	@BindView(R.id.inbound_location_detail_main_loadView)
	LoadTipFailedLayout loadTipFailedLayout;

	/**
	 * 为定位
	 */
	@BindView(R.id.un_location_tv)
	TextView notLocatedTv;

	@BindView(R.id.unlocation_line)
	View notLocatedLineView;

	/**
	 * 已定位
	 */
	@BindView(R.id.located_tv)
	TextView hadLocatedTv;

	@BindView(R.id.had_location_line)
	View hadLocatedLineView;

	/**
	 * 添加新定位按钮
	 */
	@BindView(R.id.add_location_tv)
	TextView addNewPositionBtn;

	/**
	 * 批量定位
	 */
	@BindView(R.id.location_lot_tv)
	TextView batchPositionBtn;

	/**
	 * 定位列表
	 */
	@BindView(R.id.location_rc)
	MaxRecyclerView workRecyclerView;


	@BindView(R.id.common_letter_of_notice_info_noticeLetterNoTv)
	TextView orderTitle;
	@BindView(R.id.common_letter_of_notice_info_showNoticeLetterNo)
	TextView orderNo;//移库单号
	@BindView(R.id.common_letter_of_notice_info_positionStatusName)
	TextView orderStatesName;//订单状态
	@BindView(R.id.common_letter_of_notice_info_firstTv)
	TextView creteTimeTitle;
	@BindView(R.id.common_letter_of_notice_info_showFirstValue)
	TextView creteTime;//建单时间
	@BindView(R.id.common_letter_of_notice_info_secondTv)
	TextView moveTypeTitle;
	@BindView(R.id.common_letter_of_notice_info_showSecondValue)
	TextView moveTypeName;//移库类型
	@BindView(R.id.common_letter_of_notice_info_thirdTv)
	TextView outWhTitle;
	@BindView(R.id.common_letter_of_notice_info_showThirdValue)
	TextView outWhName;//移出仓库
	@BindView(R.id.common_letter_of_notice_info_fourthTv)
	TextView inWhTitle;
	@BindView(R.id.common_letter_of_notice_info_showFourthValue)
	TextView inWhName;//移入仓库

	@BindView(R.id.materail_detail_ly)
	RelativeLayout materieInfoLayout;
	@BindView(R.id.common_materiel_position_info_showFirstValue)
	TextView showMaterielFirstValue;//物料编码
	@BindView(R.id.common_materiel_position_info_showSecondValue)
	TextView showMaterielSecondValue;//物料名称
	@BindView(R.id.common_materiel_position_info_showThirdValue)
	TextView showMaterielThirdValue;//总数
	@BindView(R.id.common_materiel_position_info_fourthTv)
	TextView materielFourthTv;
	@BindView(R.id.common_materiel_position_info_showFourthValue)
	TextView showMaterielFourthValue;//未定位数量、已定位数量

	private TransferDetails transferDetails;
	private ArrayList<WorkInfoBean> notJobInfo;//未作业信息
	private ArrayList<WorkInfoBean> hasJobInfo;//已作业信息
	boolean isWorkDone = false;

	int currentSelectedMaterielPosition=0;//当前物料选中的item位置
	int currentSelectedWorkPosition=0;//当前作业列表选中的item位置
	int itemConunt=-1;

	ArrayList<WorkNotesBean> remarks ;
	/**
	 * 物料列表
	 */
	CommonNormalAdapter materielAdapter;
	int materielAdapterFlag;
	List<BaseItemBean> itemMaterielList;

	/**
	 * 作业列表
	 */
	CommonNormalAdapter workAdapter;
	List<BaseItemBean> itemList;
	int workAdapterFlag;

	TransGoodsBean transGoodsBean;
	private String totalWeight = "";


	@Override
	protected int getLayoutResource() {
		return R.layout.activity_normal_detail_main;
	}

	@Override
	protected void initView() {
		super.initView();
		EventBus.getDefault().register(this);
		showLeftBack();
		setTitleShow("移库收货详情");
		orderTitle.setText("移库单号");
		creteTimeTitle.setText("建单时间：");
		moveTypeTitle.setText("移库类型：");
		outWhTitle.setText("移出仓库：");
		inWhTitle.setText("移入仓库：");
		addNewPositionBtn.setVisibility(View.GONE);
		batchPositionBtn.setText("添加新作业");

		setRightHomeClick(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ToastUtil.showToast(TransferGoodsConfirmDetailActivity.this, "home");
			}
		});

		setRightScanClick(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ToastUtil.showToast(TransferGoodsConfirmDetailActivity.this, "scan");
				Utils.startScanActivity(TransferGoodsConfirmDetailActivity.this);
			}
		});
	}

	@Override
	protected void initLoadingView() {
		super.initLoadingView();
		loadTipFailedLayout.setRestartOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				getTransferDetails();
			}
		});
	}

	@Override
	protected void initListener() {
		super.initListener();
		InterfaceUtil.getInstance().setInterfaceCallBackListener(interfacesCallBackListener);
	}
	InterfaceUtil.InterfacesCallBackListener  interfacesCallBackListener=new InterfaceUtil.InterfacesCallBackListener() {
		@Override
		public void onSuccess(BaseInfo<?> baseInfo, Enum opertateFlagEnum) {
			if (opertateFlagEnum== OperateFlagEnum.NOTICE_JOB_DETAIL_FOR_SAVE_WORK){//保存作业
				ToastUtil.showToast(TransferGoodsConfirmDetailActivity.this, "保存成功");
			}else if(opertateFlagEnum==OperateFlagEnum.MOVER_DELETE_WORK){//删除
				ToastUtil.showToast(TransferGoodsConfirmDetailActivity.this, "删除成功");
			}
			transferDetails = null;
			itemList.clear();
			itemMaterielList.clear();
			notJobInfo.clear();
			hasJobInfo.clear();
			remarks.clear();
			isWorkDone = false;
			isHadLocation(isWorkDone);
			getTransferDetails();
		}

		@Override
		public void onFailure(String message, Enum opertateFlagEnum) {
			ToastUtil.showToast(TransferGoodsConfirmDetailActivity.this, message);
		}

		@Override
		public void onSuccess(BaseInfo<?> baseInfo) {

		}

		@Override
		public void onFailure(String message) {

		}
	};
	@Override
	protected void initData(Bundle savedInstanceState) {
		super.initData(savedInstanceState);
		transGoodsBean = (TransGoodsBean) getIntent().getSerializableExtra("TransGoodsBean");
		activityFlag = getIntent().getIntExtra(Constants.FLAG_ACTIVITY_KEY, Constants.FLAG_ACTIVITY_IN_BOUND_LOCATION_UI);

		moveTypeName.setText(transGoodsBean.orderTypeName);
		orderNo.setText(transGoodsBean.orderNo);
		orderStatesName.setText(transGoodsBean.noticeOrderStatusName);
		creteTime.setText(StringUtils.isEmpty(String.valueOf(transGoodsBean.addTime)) ? ""
				: DateUtils.getSimpleDateTimeByMill(String.valueOf(transGoodsBean.addTime), DateUtils.DATE_TIME_FORMAT));
		outWhName.setText(transGoodsBean.tfOutWhName);
		inWhName.setText(transGoodsBean.tfInWhName);


		itemMaterielList = new ArrayList<>();
		itemList = new ArrayList<>();
		notJobInfo = new ArrayList<>();
		hasJobInfo = new ArrayList<>();
		remarks = new ArrayList<>();


		notLocatedTv.setText("未作业");
		hadLocatedTv.setText("已作业");

		isWorkDone = false;
		isHadLocation(isWorkDone);

		materielAdapterFlag = CommonNormalAdapter.FLAG_NOTICE_OUT_BOUND_DETAILS_MATREIEL_MAIN;
		workAdapterFlag = CommonNormalAdapter.FLAG_NOTICE_OUT_BOUND_DETAILS_WORK_MAIN;

		getTransferDetails();


	}

	@Override
	protected void initRecyclerView() {

		/**
		 * 物料列表
		 */
		RecyclerViewUtil.initLinearLayoutHorizontal(this, materielRecyclerView);
		materielAdapter = CommonNormalAdapterUtil.initCommonNormalAdapter(R.layout.materiel_position_info_item, itemList, materielAdapterFlag);
		materielAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
			@Override
			public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
				showNoOrHadWorkInfo(position);
			}
		});
		materielRecyclerView.setAdapter(materielAdapter);

		/**
		 * 作业列表
		 */
		RecyclerViewUtil.initLinearLayoutVERTICAL(this, workRecyclerView);
		workAdapter= CommonNormalAdapterUtil.initCommonNormalAdapter(R.layout.work_info_item, itemList, workAdapterFlag);
		/**
		 * 作业列表item点击事件
		 * 删除点击、保存作业点击
		 */
		workAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
			@Override
			public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
				currentSelectedWorkPosition=position;
				singleLocationItemClick(position, view);
			}
		});
		workRecyclerView.setAdapter(workAdapter);

	}

	@OnClick({R.id.un_location_tv, R.id.located_tv, R.id.add_location_tv, R.id.location_lot_tv})
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
			case R.id.un_location_tv://未作业
				isWorkDone=false;
				isHadLocation(isWorkDone);
				dealWorkData(notJobInfo);
				showNoOrHadWorkInfo(0);
				break;
			case R.id.located_tv://已作业
				isWorkDone = true;
				isHadLocation(isWorkDone);
				dealWorkData(hasJobInfo);
				showNoOrHadWorkInfo(0);
				break;
			case R.id.location_lot_tv://添加新作业
				itemConunt++;
				addWorkItem(itemConunt);
				break;
		}
	}

	/**
	 * 是否作业
	 *
	 * @param isLocation
	 */
	private void isHadLocation(boolean isLocation) {
		if (!isLocation) {
			notLocatedLineView.setVisibility(View.VISIBLE);
			hadLocatedLineView.setVisibility(View.INVISIBLE);
			batchPositionBtn.setVisibility(View.VISIBLE);
			notLocatedTv.setTextColor(getResources().getColor(R.color.blue));
			hadLocatedTv.setTextColor(getResources().getColor(R.color.color_gray));
		} else {
			hadLocatedLineView.setVisibility(View.VISIBLE);
			notLocatedLineView.setVisibility(View.INVISIBLE);
			batchPositionBtn.setVisibility(View.VISIBLE);
			hadLocatedTv.setTextColor(getResources().getColor(R.color.blue));
			notLocatedTv.setTextColor(getResources().getColor(R.color.color_gray));
		}
	}

	/**
	 * 获取移库发货详情
	 */
	private void getTransferDetails() {
		loadTipFailedLayout.setLoadText(R.string.since_help_loading);
		loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_PROGRESS);
		HttpManger httpManger = HttpManger.getInstance();
		httpManger.setContext(this);
		httpManger.getTransferDetails(transGoodsBean.noticeOrderId);
		httpManger.setHttpResponseCallBackListener(new HttpManger.HttpResponseCallBackListener() {
			@Override
			public void onSuccess(BaseInfo<?> baseInfo) {
				transferDetails = (TransferDetails) baseInfo.getData();
				if (transferDetails != null) {
					loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_FINISH);

					/**
					 * 未作业数据
					 */
					if (transferDetails.getNotJobInfo()!=null){
						notJobInfo.addAll(transferDetails.getNotJobInfo());
						if (notJobInfo.size()>0){
							for (int i=0; i<notJobInfo.size(); i++){
								if (i==0){
									notJobInfo.get(i).isSelected=true;
								}else {
									notJobInfo.get(i).isSelected=false;
								}
							}
						}
					}
					if (transferDetails.getHasJobInfo()!=null){
						hasJobInfo.addAll(transferDetails.getHasJobInfo());
						if (hasJobInfo.size()>0){
							for (int i=0; i<hasJobInfo.size(); i++){
								if (i==0){
									hasJobInfo.get(i).isSelected=true;
								}else {
									hasJobInfo.get(i).isSelected=false;
								}
							}
						}
					}
					dealWorkData(notJobInfo);
					showNoOrHadWorkInfo(0);
					rs.scrollTo(0,0);

				} else {
					loadTipFailedLayout.setTextColor(R.color.color_gray);
					loadTipFailedLayout.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
					loadTipFailedLayout.setNormalText(R.string.noMessage);
					loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_NORMAL);
				}


			}


			@Override
			public void onFailure(String message) {
				loadTipFailedLayout.setTextColor(R.color.color_gray);
				loadTipFailedLayout.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
				loadTipFailedLayout.setNormalText(R.string.since_help_load_failed);
				loadTipFailedLayout.setState(LoadTipFailedLayout.STATE_FAILED);
				ToastUtil.showToast(TransferGoodsConfirmDetailActivity.this, message);
			}
		});
	}


	/**
	 * 处理未作业、已作业列表数据（物料）
	 * @param materielWorkInfoBeanList
	 */
	private void dealWorkData(ArrayList<WorkInfoBean> materielWorkInfoBeanList){
		itemMaterielList.clear();
		if (materielWorkInfoBeanList.size() > 0) {
			for (WorkInfoBean workInfoBean : materielWorkInfoBeanList) {
				itemMaterielList.add(new BaseItemBean(workInfoBean));
			}
			setWorkUIIsShow(true);
			if(!isWorkDone){
				batchPositionBtn.setVisibility(View.VISIBLE);
			}else{
				batchPositionBtn.setVisibility(View.GONE);
			}

		} else {
			setWorkUIIsShow(false);
			batchPositionBtn.setVisibility(View.GONE);
		}
		materielAdapter.setNewData(itemMaterielList);
	}

	/**
	 * 处理未作业物料item点击后，对应的作业数据
	 * @param positionInfoList
	 */
	private void dealPositionData(ArrayList<PositionInfoBean> positionInfoList){
		itemList.clear();
		if (positionInfoList.size()>0){
			for (PositionInfoBean positionInfoBean: positionInfoList){
				itemList.add(new BaseItemBean(positionInfoBean));
			}
			workRecyclerView.setVisibility(View.VISIBLE);
		}else {
			workRecyclerView.setVisibility(View.INVISIBLE);
		}
		workAdapter.setNewData(itemList);
		itemConunt=itemList.size();
	}

	/**
	 * 处理已作业物料item点击后，对应的作业数据
	 * @param jobInfoBeanList
	 */
	private void dealJobInfoData(ArrayList<JobInfoBean> jobInfoBeanList){
		itemList.clear();
		if (jobInfoBeanList.size()>0){
			for (JobInfoBean jobInfoBean: jobInfoBeanList){
				itemList.add(new BaseItemBean(jobInfoBean));
			}
			workRecyclerView.setVisibility(View.VISIBLE);
		}else {
			workRecyclerView.setVisibility(View.INVISIBLE);
		}
		workAdapter.setNewData(itemList);
		itemConunt=itemList.size();
	}

	/**
	 * 展示当前未作业或者已作业信息
	 * @param currentPosition
	 */
	private void showNoOrHadWorkInfo(int currentPosition){
		if (itemMaterielList.size()<=0){
			return;
		}
		WorkInfoBean workInfoBean= (WorkInfoBean) itemMaterielList.get(currentPosition).object;
		if (workInfoBean!=null){
			showMaterielFirstValue.setText(workInfoBean.skuCode);
			showMaterielSecondValue.setText(workInfoBean.skuName);
			totalWeight = workInfoBean.detailWeight+"";
			showMaterielThirdValue.setText(workInfoBean.detailAmount+"件/"+workInfoBean.detailWeight+"吨");
			if(!isWorkDone){
				showMaterielFourthValue.setText(workInfoBean.notJobAmount+"件/"+workInfoBean.notJobWeight+"吨");
			}else{
				showMaterielFourthValue.setText(workInfoBean.jobAmount+"件/"+workInfoBean.jobWeight+"吨");
			}
		}

		for (BaseItemBean baseItemBean : itemMaterielList){
			((WorkInfoBean)baseItemBean.object).isSelected=false;
		}

		((WorkInfoBean) itemMaterielList.get(currentPosition).object).isSelected=true;
		materielAdapter.setNewData(itemMaterielList);
		if (!isWorkDone){
			materielFourthTv.setText(getResourcesString(R.string.notWorkingNumber));
			if (workInfoBean!=null && workInfoBean.getPositionInfoList()!=null){
				dealPositionData(workInfoBean.getPositionInfoList());
			}else {
				workRecyclerView.setVisibility(View.INVISIBLE);
			}
		}else {
			materielFourthTv.setText(getResourcesString(R.string.hasWorkingNumber));
			if (workInfoBean!=null && workInfoBean.getJobInfoList()!=null){
				dealJobInfoData(workInfoBean.getJobInfoList());
			}else {
				workRecyclerView.setVisibility(View.INVISIBLE);
			}
		}
	}

	/**
	 * 设置未作业、已作业模块是否展示
	 * @param isHasData
	 */
	private void setWorkUIIsShow(boolean isHasData){
		if (isHasData){
			materielRecyclerView.setVisibility(View.VISIBLE);
			materieInfoLayout.setVisibility(View.VISIBLE);
			workRecyclerView.setVisibility(View.VISIBLE);
		}else {
			materielRecyclerView.setVisibility(View.GONE);
			materieInfoLayout.setVisibility(View.GONE);
			workRecyclerView.setVisibility(View.GONE);
		}
	}


	/**
	 * 单个物料item下定位列表的item上点击事件
	 * 未作业模块（单个保存作业操作）
	 * @param tempCurrentSelectedWorkPosition 当前作业列表点击item的position
	 * @param view
	 */
	private void singleLocationItemClick(int tempCurrentSelectedWorkPosition, View view) {
		EditText edtShowNumberForPiece = (EditText) workAdapter.getViewByPosition(workRecyclerView, tempCurrentSelectedWorkPosition, R.id.work_info_item_showNumberForPieceTv);
		EditText edtShowWeightForTon = (EditText) workAdapter.getViewByPosition(workRecyclerView, tempCurrentSelectedWorkPosition, R.id.work_info_item_showWeightForTonTv);
		EditText edtShowVolumeForSquare = (EditText) workAdapter.getViewByPosition(workRecyclerView, tempCurrentSelectedWorkPosition, R.id.work_info_item_showVolumeForSquareTv);
		EditText edtShowRemark = (EditText) workAdapter.getViewByPosition(workRecyclerView, tempCurrentSelectedWorkPosition, R.id.work_info_item_showRemarksTv);
		//当前选中的物料item对象
		WorkInfoBean currentMaterielPositionInfoBean = (WorkInfoBean) itemMaterielList.get(currentSelectedMaterielPosition).object;

		String ids="";
		SaveTransferGoodsRequest saveTransferGoodsRequest = new SaveTransferGoodsRequest();
		saveTransferGoodsRequest.orderId = transGoodsBean.orderId;
		saveTransferGoodsRequest.orderNo = transGoodsBean.orderNo;
		saveTransferGoodsRequest.noticeOrderId = transGoodsBean.noticeOrderId;
		saveTransferGoodsRequest.noticeOrderNo = transGoodsBean.noticeOrderNo;
		saveTransferGoodsRequest.skuId = currentMaterielPositionInfoBean.skuId;
		saveTransferGoodsRequest.skuCode = currentMaterielPositionInfoBean.skuCode;
		saveTransferGoodsRequest.skuName = currentMaterielPositionInfoBean.skuName;

		BaseItemBean baseItemBean =itemList.get(tempCurrentSelectedWorkPosition);
		if (!isWorkDone){
			PositionInfoBean positionInfoBean = (PositionInfoBean) baseItemBean.object;
			saveTransferGoodsRequest.orderDetailId = positionInfoBean.orderDetailId;
			saveTransferGoodsRequest.noticeOrderDetailId = positionInfoBean.noticeOrderDetailId;
			saveTransferGoodsRequest.actualStockId = positionInfoBean.actualStockId;
			saveTransferGoodsRequest.invId = positionInfoBean.actualWhId;
			saveTransferGoodsRequest.packageWeight = positionInfoBean.packageWeight;
			saveTransferGoodsRequest.actualAmount = positionInfoBean.actualAmount;
			saveTransferGoodsRequest.actualWeight = positionInfoBean.actualWeight;
			saveTransferGoodsRequest.actualVolume = positionInfoBean.actualVolume;
			saveTransferGoodsRequest.stockStatus = positionInfoBean.stockStatus;
			saveTransferGoodsRequest.stockType = positionInfoBean.stockType;
			saveTransferGoodsRequest.unitId = positionInfoBean.unitId;
			saveTransferGoodsRequest.batchNo = positionInfoBean.batchNo;
			saveTransferGoodsRequest.remark = positionInfoBean.remark;
			ids = positionInfoBean.id;
			saveTransferGoodsRequest.setJobAmountList(positionInfoBean.getJobAmountList());
			saveTransferGoodsRequest.setJobAttachList(positionInfoBean.getJobAttachList());
		}else {
			JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
			saveTransferGoodsRequest.orderDetailId = jobInfoBean.orderDetailId;
			saveTransferGoodsRequest.noticeOrderDetailId = jobInfoBean.noticeOrderDetailId;
			saveTransferGoodsRequest.actualStockId = jobInfoBean.actualStockId;
			saveTransferGoodsRequest.invId = jobInfoBean.actualWhId;
			saveTransferGoodsRequest.packageWeight = jobInfoBean.packageWeight;
			saveTransferGoodsRequest.actualAmount = jobInfoBean.actualAmount;
			saveTransferGoodsRequest.actualWeight = jobInfoBean.actualWeight;
			saveTransferGoodsRequest.actualVolume = jobInfoBean.actualVolume;
			saveTransferGoodsRequest.stockStatus = jobInfoBean.stockStatus;
			saveTransferGoodsRequest.stockType = jobInfoBean.stockType;
			saveTransferGoodsRequest.unitId = jobInfoBean.unitId;
			saveTransferGoodsRequest.batchNo = jobInfoBean.batchNo;
			saveTransferGoodsRequest.remark = jobInfoBean.remark;
			ids=jobInfoBean.id;
			saveTransferGoodsRequest.id = ids;
			saveTransferGoodsRequest.setJobAmountList(jobInfoBean.getJobAmountList());
			saveTransferGoodsRequest.setJobAttachList(jobInfoBean.getJobAttachList());
		}
		/**
		 * 保存当前item编辑的数量、重量、体积数据。防止在编辑完后，选择库存状态、库存类型等其他操作返回到当前界面时，编辑的数据被刷新至初始数据
		 */
		if (!isWorkDone){
			PositionInfoBean positionInfoBean = (PositionInfoBean) baseItemBean.object;
			positionInfoBean.amount = positionInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
			positionInfoBean.weight = positionInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
			positionInfoBean.volume = positionInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
		}else {
			JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
			jobInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
			jobInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
			jobInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
			jobInfoBean.amount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
			jobInfoBean.weight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
			jobInfoBean.volume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
		}

		Intent intent = null;
		String action = "";
		int reqCode = -1;
		switch (view.getId()){
			case R.id.work_info_item_sureWorkBtn://确认该作业
				/**
				 * ids为空时，该item无数据，为新加的item
				 */
				if (!isWorkDone){
					PositionInfoBean positionInfoBean= (PositionInfoBean) baseItemBean.object;
					positionInfoBean.amount = positionInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
					positionInfoBean.weight = positionInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
					positionInfoBean.volume = positionInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
				}else {
					JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
					jobInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
					jobInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
					jobInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
					jobInfoBean.amount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
					jobInfoBean.weight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
					jobInfoBean.volume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
				}
				if (StringUtils.isEmpty(saveTransferGoodsRequest.actualStockId)){
					ToastUtil.showToast(TransferGoodsConfirmDetailActivity.this, getResourcesString(R.string.toastPleaseSeletedStockPosition));
					return;
				}
				if (StringUtils.isEmpty(saveTransferGoodsRequest.invId)){
					ToastUtil.showToast(TransferGoodsConfirmDetailActivity.this, getResourcesString(R.string.toastPleaseSeletedWareHouse));
					return;
				}

				if (checkNumberIsEmpty(edtShowNumberForPiece, getResourcesString(R.string.toastNumberNotEmpty))){
					return;
				}
				if (checkNumberIsEmpty(edtShowWeightForTon, getResourcesString(R.string.toastWeightNotEmpty))){
					return;
				}
				/*if (checkNumberIsEmpty(edtShowVolumeForSquare, getResourcesString(R.string.toastVolumeNotEmpty))){
					return;
				}*/

				if (checkNumberIsMoreThanZero(edtShowNumberForPiece, getResourcesString(R.string.toastNumberMustMoreThanZero))){
					return;
				}
				if (checkNumberIsMoreThanZero(edtShowWeightForTon, getResourcesString(R.string.toastWeightMustMoreThanZero))){
					return;
				}
				/*if (checkNumberIsMoreThanZero(edtShowVolumeForSquare, getResourcesString(R.string.toastVolumeMustMoreThanZero))){
					return;
				}*/
//                }
				//获取当前提交时的数量、重量、体积值
				saveTransferGoodsRequest.actualAmount = BigDecimalUtil.getBigDecimalByString(edtShowNumberForPiece.getText().toString());
				saveTransferGoodsRequest.actualWeight = BigDecimalUtil.getBigDecimalByString(edtShowWeightForTon.getText().toString());
				saveTransferGoodsRequest.actualVolume = BigDecimalUtil.getBigDecimalByString(edtShowVolumeForSquare.getText().toString());
				saveTransferGoodsRequest.remark = edtShowRemark.getText().toString().trim();
				InterfaceUtil.getInstance().saveTransferGoodsDetail(saveTransferGoodsRequest, OperateFlagEnum.NOTICE_JOB_DETAIL_FOR_SAVE_WORK,
						TransferGoodsConfirmDetailActivity.this, isWorkDone);
				break;
			case R.id.work_info_item_workDeleteTv://删除该作业
				if (StringUtils.isEmpty(ids)){//此时该item无数据，为新增的item，故直接将列表item删除即可，无需调用接口
					itemConunt--;
					itemList.remove(tempCurrentSelectedWorkPosition);
					workAdapter.setNewData(itemList);
					return;
				}
				InterfaceUtil.getInstance().deleteTransferGoodsWork(ids, OperateFlagEnum.MOVER_DELETE_WORK,
						TransferGoodsConfirmDetailActivity.this);
				break;
			case R.id.work_info_item_showReservoirPositionTv://库位选择
				intent = new Intent(this, DepotSelectActivity.class);
				reqCode = AppConfig.BaseDataAction.REQCODE_NOTICE_OUT_BOUND_DETAIL_BY_DEPOT;
				startActivityForResult(intent, reqCode);
				break;
			case R.id.work_info_item_showStorehouseTv://跳转仓库选择列表
				intent = new Intent(this, SelectBaseDataActivity.class);
				action = AppConfig.BaseDataAction.WARE_HOUSE_TYPE_0;
				reqCode = AppConfig.BaseDataAction.REQCODE_NOTICE_OUT_BOUND_DETAIL;
				intent.putExtra("action", action);
				startActivityForResult(intent, reqCode);
				break;
			case R.id.work_info_item_showInventoryStatusTv://跳转库存状态列表
				intent = new Intent(this, SelectBaseDataActivity.class);
				action = AppConfig.BaseDataAction.STO_INVENTORY_STOCK_STATUS;
				reqCode = AppConfig.BaseDataAction.REQCODE_STO_INVENTORY_STOCK_STATUS;
				intent.putExtra("action", action);
				startActivityForResult(intent, reqCode);
				break;
			case R.id.work_info_item_showInventoryTypeTv://跳转库存类型列表
				intent = new Intent(this, SelectBaseDataActivity.class);
				action = AppConfig.BaseDataAction.STO_INVENTORY_STOCK_TYPE;
				reqCode = AppConfig.BaseDataAction.REQCODE_STO_INVENTORY_STOCK_TYPE;
				intent.putExtra("action", action);
				startActivityForResult(intent, reqCode);
				break;
			case R.id.work_info_item_showJobRecordTv://作业记录
				remarks = saveTransferGoodsRequest.getJobAmountList();
				intent = new Intent(this, OperateRemarkActivity.class);
				intent.putExtra("OperateRemark",remarks);
				intent.putExtra("TotolWeight",totalWeight);
				startActivityForResult(intent, AppConfig.BaseDataAction.REQCODE_JOB_RECORD);
				break;
		}

	}

	/**
	 * 添加新作业数据
	 * @param itemConunt 当前列表item的总数
	 */
	public void addWorkItem(final int itemConunt) {
		/**
		 * 设置当前添加itemView的位置，从0开始计算，故position=itemConunt-1
		 */
		final int position = itemConunt-1;
		if (!isWorkDone){
			PositionInfoBean positionInfoBean=new PositionInfoBean();
			positionInfoBean.amount = BigDecimalUtil.getBigDecimalByString("0");
			positionInfoBean.weight = BigDecimalUtil.getBigDecimalByString("0");
			positionInfoBean.volume = BigDecimalUtil.getBigDecimalByString("0");
			positionInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString("0");
			positionInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString("0");
			positionInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString("0");
			itemList.add(position, new BaseItemBean(positionInfoBean));
		}else {
			JobInfoBean jobInfoBean = new JobInfoBean();
			jobInfoBean.amount = BigDecimalUtil.getBigDecimalByString("0");
			jobInfoBean.actualAmount = BigDecimalUtil.getBigDecimalByString("0");
			jobInfoBean.weight=BigDecimalUtil.getBigDecimalByString("0");
			jobInfoBean.actualWeight = BigDecimalUtil.getBigDecimalByString("0");
			jobInfoBean.volume= BigDecimalUtil.getBigDecimalByString("0");
			jobInfoBean.actualVolume = BigDecimalUtil.getBigDecimalByString("0");
			itemList.add(position, new BaseItemBean(jobInfoBean));
		}
		workRecyclerView.smoothScrollToPosition(position);
		workAdapter.setNewData(itemList);
		workRecyclerView.setVisibility(View.VISIBLE);
		workAdapter.notifyDataSetChanged();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == HEAD_ABLUME | requestCode == HEAD_CAREAM){
			switch (requestCode){
				case HEAD_ABLUME://相册返回
					// 判断手机版本，因为在4.4版本都手机处理图片返回的方法就不一样了
					//4.4以后返回的不是真实的uti而是一个封装过后的uri 所以要对封装过后的uri进行解析
					if (data!=null){
						if (Build.VERSION.SDK_INT >= 19) {
							//4.4系统一上用该方法解析返回图片
							displayImage(handleImageOnKitKat(data));
						} else {
							//4.4一下用该方法解析图片的获取
							displayImage(handleImageBeforeKitKat(data));
						}
					}
					break;
				case HEAD_CAREAM://相机
					if (data != null){
						Bundle bundle = data.getExtras();
						if (bundle != null){//照相后，点击取消时，该bundle为空
							Bitmap bitmap = (Bitmap) bundle.get("data");
							String fileName = FileUtils.saveImage(bitmap);//保存照相的图片
							Uri uri = Uri.fromFile(FileUtils.getFile(fileName));
							displayImage(FileUtils.getRealFilePathToUri(TransferGoodsConfirmDetailActivity.this, uri));
						}
					}
					break;
			}
			return;
		}

		BaseItemBean baseItemBean = itemList.get(currentSelectedWorkPosition);
		/**
		 * 获取作业记录数据
		 */
		if (data != null && requestCode == AppConfig.BaseDataAction.REQCODE_JOB_RECORD) {
			remarks = (ArrayList<WorkNotesBean>) data.getSerializableExtra("remarks");
			if (remarks.size() > 0) {
				String workNoteName = "";
				for (int i = 0; i < remarks.size(); i++) {
					if (StringUtils.isBlank(workNoteName))
						workNoteName = remarks.get(i).getDepart();
					else
						workNoteName = workNoteName + "," + remarks.get(i).getDepart();
				}
				if (!isWorkDone){
					PositionInfoBean positionInfoBean= (PositionInfoBean) baseItemBean.object;
					positionInfoBean.jobRecord = workNoteName;
					positionInfoBean.setJobAmountList(remarks);
					baseItemBean.object = positionInfoBean;
				}else {
					JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
					jobInfoBean.jobRecord = workNoteName;
					jobInfoBean.setJobAmountList(remarks);
					baseItemBean.object = jobInfoBean;
				}
				workAdapter.notifyItemChanged(currentSelectedWorkPosition);
			}
			return;
		}
		/**
		 * 获取库存状态、库存类型等数据
		 */
		if (data == null || data.getSerializableExtra("selectBean") == null)
			return;
		switch (requestCode){
			case AppConfig.BaseDataAction.REQCODE_NOTICE_OUT_BOUND_DETAIL:
				SelectDictionaryBean selectBean = (SelectDictionaryBean) data.getSerializableExtra("selectBean");
				if (!isWorkDone){
					PositionInfoBean positionInfoBean = (PositionInfoBean) baseItemBean.object;
					positionInfoBean.whName = selectBean.getText();
					positionInfoBean.whId = selectBean.getValue();
					positionInfoBean.actualWhId = selectBean.getValue();
					baseItemBean.object = positionInfoBean;
				}else {
					JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
					jobInfoBean.whName = selectBean.getText();
					jobInfoBean.whId = selectBean.getValue();
					jobInfoBean.actualWhId = selectBean.getValue();
					baseItemBean.object = jobInfoBean;
				}
				workAdapter.notifyItemChanged(currentSelectedWorkPosition);
				break;
			case AppConfig.BaseDataAction.REQCODE_NOTICE_OUT_BOUND_DETAIL_BY_DEPOT:
				SearchStockBean searchStockBean= (SearchStockBean) data.getSerializableExtra("selectBean");
				if (!isWorkDone){
					PositionInfoBean positionInfoBean = (PositionInfoBean) baseItemBean.object;
					positionInfoBean.stockName = searchStockBean.getStockName();
					positionInfoBean.stockId = searchStockBean.getStockId();
					positionInfoBean.actualStockId = searchStockBean.getStockId();
					baseItemBean.object = positionInfoBean;
				}else {
					JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
					jobInfoBean.stockName = searchStockBean.getStockName();
					jobInfoBean.stockId = searchStockBean.getStockId();
					jobInfoBean.actualStockId = searchStockBean.getStockId();
					baseItemBean.object = jobInfoBean;
				}
				workAdapter.notifyItemChanged(currentSelectedWorkPosition);
				break;
			case AppConfig.BaseDataAction.REQCODE_STO_INVENTORY_STOCK_STATUS://库存状态
				selectBean= (SelectDictionaryBean) data.getSerializableExtra("selectBean");
				if (!isWorkDone){
					PositionInfoBean positionInfoBean = (PositionInfoBean) baseItemBean.object;
					positionInfoBean.stockStatusName = selectBean.getText();
					positionInfoBean.stockStatus = selectBean.getValue();
					baseItemBean.object = positionInfoBean;
				}else {
					JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
					jobInfoBean.stockStatusName = selectBean.getText();
					jobInfoBean.stockStatus = selectBean.getValue();;
					baseItemBean.object = jobInfoBean;
				}
				workAdapter.notifyItemChanged(currentSelectedWorkPosition);
				break;
			case AppConfig.BaseDataAction.REQCODE_STO_INVENTORY_STOCK_TYPE://库存类型
				selectBean = (SelectDictionaryBean) data.getSerializableExtra("selectBean");
				if (!isWorkDone){
					PositionInfoBean positionInfoBean = (PositionInfoBean) baseItemBean.object;
					positionInfoBean.stockTypeName = selectBean.getText();
					positionInfoBean.stockType = selectBean.getValue();
					baseItemBean.object = positionInfoBean;
				}else {
					JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
					jobInfoBean.stockTypeName = selectBean.getText();
					jobInfoBean.stockType = selectBean.getValue();
					baseItemBean.object = jobInfoBean;
				}
				workAdapter.notifyItemChanged(currentSelectedWorkPosition);
				break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 校验数量、重量、体积是否为空
	 * @param editText
	 * @param message
	 */
	private boolean checkNumberIsEmpty(EditText editText, String message){
		if (StringUtils.isEmpty(editText.getText().toString())){
			ToastUtil.showToast(TransferGoodsConfirmDetailActivity.this, message);
			return true;
		}
		return false;
	}

	/**
	 * 校验数量、重量、体积是否大于0
	 * @param editText
	 * @param message
	 */
	private boolean checkNumberIsMoreThanZero(EditText editText, String message){
		if (Float.parseFloat(editText.getText().toString())<=0){
			ToastUtil.showToast(TransferGoodsConfirmDetailActivity.this, message);
			return true;
		}
		return false;
	}
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEventMainThread(final EventBusImage eventBusImage){
		currentSelectedWorkPosition=eventBusImage.currentItemPosition;
		openAblumeOrCaream(eventBusImage.flag);
	}

	/**
	 * 打开相册或者相机
	 * @param flag
	 */
	private void openAblumeOrCaream(int flag){
		switch (flag){
			case HEAD_ABLUME://相册
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, HEAD_ABLUME);
				break;
			case HEAD_CAREAM://相机
				Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(camera, HEAD_CAREAM);
				break;
		}
	}

	/**
	 * 通过imagepath来绘制immageview图像
	 *
	 * @param imagPath
	 */
	protected void displayImage(String imagPath) {
		if (imagPath != null) {
			JobAttachBean jobAttachBean = new JobAttachBean();
			jobAttachBean.attachUrl = imagPath;
			ArrayList<JobAttachBean> imageList = new ArrayList<>();
			imageList.add(jobAttachBean);
			BaseItemBean baseItemBean=itemList.get(currentSelectedWorkPosition);
			if (!isWorkDone){
				PositionInfoBean positionInfoBean = (PositionInfoBean) baseItemBean.object;
				positionInfoBean.imagePath = imagPath;
				positionInfoBean.setJobAttachList(imageList);
				baseItemBean.object = positionInfoBean;
			}else {
				JobInfoBean jobInfoBean = (JobInfoBean) baseItemBean.object;
				jobInfoBean.setJobAttachList(imageList);
				jobInfoBean.imagePath = imagPath;
				baseItemBean.object = jobInfoBean;
			}
			workAdapter.notifyItemChanged(currentSelectedWorkPosition);
		} else {
			ToastUtil.showToast(this, "图片获取失败");
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}
}